# coding=utf-8
from django.http import HttpResponseRedirect, HttpResponse
from django.utils.deprecation import MiddlewareMixin

from fly2018.toolkit import jwt_kit


class AuthMiddleware(MiddlewareMixin):
    """
    鉴权
    """
    white_list = [
        'adv.html',
        'adv1.html',
        'adv2.html',
        'adv3.html',
        'adv4.html',
        'fake.html',
        'permission.html',
        '.html'
        '.csv'
    ]

    def process_request(self, request):
        try:
            if request.path not in self.white_list and request.path == 'login.html':
                return

            token = request.COOKIES.get('token')
            username = request.COOKIES.get('username')

            if not token and "login.html" in request.path:
                from django.template import loader
                template = loader.get_template('app/login.html')
                response = HttpResponse(template.render(request))
                return response

            res = jwt_kit.decode_token(token)
            if not jwt_kit.verify(res):
                return HttpResponseRedirect('login.html')
            request.username = username

        except Exception as e:
            return HttpResponseRedirect('login.html')

    # def process_response(self, request, response):
    #     if hasattr(request, "username"):
    #         if request.username == "admin":
    #             pass
    #     return response

